package socket.client;

import com.alibaba.fastjson.JSON;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import socket.utils.message.Message;
import socket.utils.message.MsgType;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * Created by think on 2017/10/30.
 */
public class EchoClient {
    private final String host;
    private final int port;
    public SocketChannel socketChannel;
    private static final EventExecutorGroup group = new DefaultEventExecutorGroup(20);

    public EchoClient(String host, int port) throws InterruptedException {
        this.host = host;
        this.port = port;
        start();
    }

    public void start() throws InterruptedException {
        ChannelFuture future = null;
        EventLoopGroup eventLoopGroup = null;
        try {
            eventLoopGroup = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IdleStateHandler(20, 10, 0))
                                    .addLast(new StringEncoder(Charset.forName("UTF-8")))
                                    .addLast(new StringDecoder(Charset.forName("UTF-8")))
                                    .addLast(new EchoClientHandler());
                        }
                    });
            future = bootstrap.connect(host, port).sync();
            if (future.isSuccess()) {
                socketChannel = (SocketChannel) future.channel();
                System.out.println("connect server  成功---------");
            } else {
                System.out.println("连接失败 准备重连！");
                start();
            }
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
              /*if(null != future){
                  if(null != future.channel() && future.channel().isOpen()){
                      future.channel().close();
                  }
              }
              System.out.println("准备重连！");
              start();*/
            //优雅退出，释放NIO线程组
            eventLoopGroup.shutdownGracefully();
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        EchoClient bootstrap = new EchoClient("127.0.0.1", 8899);
        Message loginMsg = new Message(MsgType.LOGIN);
        loginMsg.setClientId("001");
        loginMsg.setTargetId("127.0.0.1");
        loginMsg.setType(MsgType.LOGIN);
        bootstrap.socketChannel.writeAndFlush(JSON.toJSON(loginMsg));
    }
}
